﻿using System;
using System.Data.Common;

using Utilities;

namespace DataAccess
{
    /// <summary>
    /// A database command to retrieve a single object
    /// </summary>
    public class ObjectDatabaseCommand<T> : QueryDatabaseCommand<T>
    {
        #region Properties

        /// <summary>
        /// The object retrieved from the database
        /// </summary>
        public T Object { get; private set; }

        #endregion

        public override int Read(DbDataReader reader)
        {
            if (reader.HasRows)
            {
                object temp = null;

                if (reader.Read())
                {
                    temp = ReadObject(reader);
                }  

                if (reader.Read())
                {
                    throw new InvalidOperationException("Query returned more than one record");
                }

                Object = (T)temp;
            };

            return Object == null ? 0 : 1;
        }
    }
}
